#import <Foundation/Foundation.h>
#import "ZipArchive.h"
#import "jingtai.h"
#import "Downloaddata.h"
#import "MHFileTool.h"
#import "PrintObject.h"

@implementation Downloaddata

@synthesize fileData1;
@synthesize  name;

- (void)star :(NSString*)lujing andModel:(M_content *)model andmyView:(MyView *)myview
{
    
    self.model = model;
    //创建下载路径
    self.name=[[[lujing stringByDeletingPathExtension] componentsSeparatedByString:@"/"] lastObject];
if([jingtai.sharedSingleton.Downloadqueue containsObject:self.name])
{
    NSLog(@"已经在下载队列中");
}
    else
    {
        [jingtai.sharedSingleton.Downloadqueue addObject:self.name];
        NSURL *url=[NSURL URLWithString:lujing];
    
        //创建一个请求
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
        //发送请求（使用代理的方式）
        NSURLConnection *connt=[NSURLConnection connectionWithRequest:request delegate:self];
        [connt start];
    }
}

#pragma mark- NSURLConnectionDataDelegate代理方法
/*
 *当接收到服务器的响应（连通了服务器）时会调用
 */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{    //初化data
       self.filesize=response.expectedContentLength;
    self.fileData1=[NSMutableData data];
    NSLog(@"要下载文件大小为 %lld",response.expectedContentLength);
    if(response.expectedContentLength<3000)
    {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"下载资源包失败！" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
    }
    else
    {
        
    }

 
}

/*
 *当接收到服务器的数据时会调用（可能会被调用多次，每次只传递部分数据）
 */
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //一点一点接收数据。
    NSData *now=self.fileData1;
       [self.fileData1 appendData:data];
    NSLog(@"接收到服务器的数据！---%f",(((float)(now.length)/(float)(self.filesize)))*100);
    NSString * a =[NSString stringWithFormat:@"%f",(((float)(now.length)/(float)self.filesize))*100];
    //UnitySendMessage("Unitysendmessage", "downloadbaifenbi", [a UTF8String]);

        
    

}

/*
 *当服务器的数据加载完毕时就会调用
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 下载完毕
    // 大文件不放Documents, 可以放Library\Caches或者tmp
    //    NSString *fullpath=[caches stringByAppendingString:@"video.zip"];
    NSString *caches = NSTemporaryDirectory();
    NSString *filepath = [caches stringByAppendingPathComponent:@"temp.zip"];
    [self.fileData1 writeToFile:filepath atomically:YES];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString * kindPath = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",self.model.kindname] ];
    NSString * shopPath = [kindPath stringByAppendingString:[NSString stringWithFormat:@"/%@",self.model.shopname]];
    if([fm fileExistsAtPath:kindPath])
    {
        
    }
    else
    {
        BOOL dirkind = [fm createDirectoryAtPath:kindPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(dirkind)
        {
            NSLog(@"创建kind文件成功");
        }
        else
        {
            NSLog(@"创建kind文件失败");
        }
    }
    if([fm fileExistsAtPath:shopPath])
    {
        
    }
    else
    {
        BOOL dirshop = [fm createDirectoryAtPath:shopPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(dirshop)
        {
            NSLog(@"创建shop文件成功");
        }
        else
        {
            NSLog(@"创建shop文件失败");
        }
    }

   // NSArray *pathtemps=NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES);
   // NSString *temppath=[pathtemps objectAtIndex:0];
    //NSString *locallujing=[NSString stringWithFormat:@"%@/%@/ditu/%@",path,jingtai.sharedSingleton.name,jingtai.sharedSingleton.name];
    dispatch_async(dispatch_get_global_queue(0,  0), ^{
        NSString *zipPath = filepath;
            ZipArchive *za = [[ZipArchive alloc] init];
        if ([za UnzipOpenFile: zipPath]) {
            BOOL ret = [za UnzipFileTo: shopPath overWrite: YES];
            if (NO == ret){} [za UnzipCloseFile];
            dispatch_async(dispatch_get_main_queue(),
                           ^{
                               NSFileManager * file=[[NSFileManager alloc] init];
                               if([file fileExistsAtPath:filepath])
                               {
                                   [file removeItemAtPath:filepath error:nil];
                               }
                               NSString *Version=[NSString stringWithFormat:@"%@/%@/Version.txt",shopPath,self.name];
                               NSString* fileContents = [NSString stringWithContentsOfFile:Version encoding:NSUTF8StringEncoding error:nil];
                               //获取路径对象
                               NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
                               //获取完整路径
                               NSString *documentsDirectory = [paths objectAtIndex:0];
                               NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Version.plist"];
                               NSMutableDictionary *dictplist ;
                               if([fm fileExistsAtPath:plistPath])
                               {
                                   dictplist =[[[NSMutableDictionary alloc]initWithContentsOfFile:plistPath]mutableCopy];
                               }
                               else
                               {
                                   dictplist = [[NSMutableDictionary alloc] init];
                               }
                               [dictplist setValue:fileContents forKey:[NSString stringWithFormat:@"%@-%@-%@",self.model.kindname,self.model.shopname,self.model.name]];
                               //写入文件
                               [dictplist writeToFile:plistPath atomically:YES];
                               NSFileManager * fm = [NSFileManager defaultManager];
                               NSString * download =[MHFileTool getLocalFilePath:@"downloaded.plist"];
                               if([fm fileExistsAtPath:download])
                               {
                                   NSMutableArray *localapplist = [[NSMutableArray alloc]initWithContentsOfFile:download];
                                   BOOL isadd =YES;
                                   for(int i =0;i<localapplist.count;i++)
                                   {
                                       NSDictionary * temp = [localapplist objectAtIndex:i];
                                     int n  =  [self.model check:self.model andtwo:temp];
                                     if(n==2)
                                     {
                                         isadd =NO;
                                         self.model.localPath = [NSString stringWithFormat:@"%@/%@/%@/ditu/%@",self.model.kindname,self.model.shopname,self.name,self.name];
                                         self.model.NameID = self.model.name;
                                         self.model.IconID = self.model.Icon;
                                         self.model.state =1;
                                         NSDictionary * dic =[PrintObject getObjectData:self.model];
                                         [localapplist replaceObjectAtIndex:i withObject:dic];
                                         [localapplist writeToFile:download atomically:YES];
                                     }
                                   }
                                   if(isadd)
                                   {
                                       self.model.localPath = [NSString stringWithFormat:@"%@/%@/%@/ditu/%@",self.model.kindname,self.model.shopname,self.name,self.name];
                                       self.model.NameID = self.model.name;
                                       self.model.IconID = self.model.Icon;
                                       self.model.state =1;
                                       NSDictionary * dic =[PrintObject getObjectData:self.model];
                                       [localapplist addObject:dic];
                                       [localapplist writeToFile:download atomically:YES];
                                   }
                               }
                               else
                               {
                                    NSMutableArray *localapplist = [[NSMutableArray alloc]init];
                                   self.model.localPath = [NSString stringWithFormat:@"%@/%@/%@/ditu/%@",self.model.kindname,self.model.shopname,self.name,self.name];
                                   self.model.NameID = self.model.name;
                                   self.model.IconID = self.model.Icon;
                                   self.model.state =1;
                                   NSDictionary * dic =[PrintObject getObjectData:self.model];
                                   [localapplist addObject:dic];
                                   [localapplist writeToFile:download atomically:YES];
                               }
                               [[jingtai sharedSingleton].contentview loadscroll:NO];
                           });
        }
    });
    
   [jingtai.sharedSingleton.Downloadqueue removeObject:self.name];
    NSLog(@"下载完毕");
  
}
/*
 *请求错误（失败）的时候调用（请求超时\断网\没有网\，一般指客户端错误）
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"下载资源包失败！" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];


    [jingtai.sharedSingleton.Downloadqueue removeObject:self.name];
}

@end